package main

import (
	"bytes"
	"context"
	"fmt"
	"strings"
	"sync"

	"github.com/PuerkitoBio/goquery"
)

//解析页面得到新的url以及img，url交给UrlContainer，img交给ImageContainer

type Page struct {
	url     string
	content []byte
}

type PageDealer struct {
	group *sync.WaitGroup
}

type PageDealerManager struct {
	Manager
}

func NewPageDealerManager() *PageDealerManager {
	return &PageDealerManager{}
}

func NewPageDealer(group *sync.WaitGroup) *PageDealer {
	return &PageDealer{group: group}
}

func (dealer *PageDealer) Run(ctx context.Context) {
	dealer.group.Add(1)
	for {
		select {
		case <-ctx.Done():
			defer dealer.group.Done()
			return
		case page := <-PageContainer:
			dealer.ParsePage(page)
		}
	}
}

func NewPage(url string, content []byte) *Page {
	return &Page{
		url:     url,
		content: content,
	}
}

func (dealer *PageDealer) ParsePage(p *Page) {
	fmt.Println("Parsing web_page,", p.url)
	doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(p.content))
	if err != nil {
		fmt.Println("ERROR! CreateDocumentFromPage ERROR")
		return
	}
	getNewPage(doc)
	getNewImage(doc)
}

func getNewPage(doc *goquery.Document) {
	doc.Find("a").Each(func(i int, s *goquery.Selection) {
		url, ok := s.Attr("href")
		if !ok {
			fmt.Println("ERROR! \"href\" is not exist")
			return
		}

		UrlContainer <- Url(url)
	})
}

func getNewImage(doc *goquery.Document) {
	doc.Find("img").Each(func(i int, s *goquery.Selection) {
		url, ok := s.Attr("src")
		if !ok {
			fmt.Println("ERROR!\"src\" is not exist")
			return
		}

		url = toAbs(url)

		image := NewImage(url)
		ImageContainer <- image
	})
}

func toAbs(url string) string {
	if strings.Index(url, "https") != 0 {
		url = "https:" + url
	}
	return url
}
